package cn.iocoder.yudao.module.system.service.application;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.module.system.controller.admin.application.vo.ApplicationPageReqVO;
import cn.iocoder.yudao.module.system.controller.admin.application.vo.ApplicationSaveReqVO;
import cn.iocoder.yudao.module.system.dal.dataobject.application.ApplicationDO;
import cn.iocoder.yudao.module.system.dal.dataobject.nodeconfig.NodeConfigDO;
import cn.iocoder.yudao.module.system.dal.mysql.application.ApplicationMapper;
import cn.iocoder.yudao.module.system.enums.application.ApplicationEnums;
import cn.iocoder.yudao.module.system.service.application.ApplicationService;
import cn.iocoder.yudao.module.system.service.nodeconfig.NodeConfigService;
import cn.iocoder.yudao.module.system.service.record.ApprovalRecordService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import org.springframework.validation.annotation.Validated;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.*;

import cn.iocoder.yudao.framework.common.util.object.BeanUtils;



import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils.getPortalLoginUserId;
import static cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils.getPortalLoginUsername;


/**
 * 目录审批 Service 实现类
 *
 * @author 芋道源码
 */
@Service
@Validated
public class ApplicationServiceImpl implements ApplicationService {

    @Resource
    private ApplicationMapper applicationMapper;
    @Resource
    private ApprovalRecordService approvalRecordService;
    @Resource
    private NodeConfigService nodeConfigService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Integer createApplication(ApplicationSaveReqVO createReqVO) throws Exception {
        // 插入
        ApplicationDO application = BeanUtils.toBean(createReqVO, ApplicationDO.class);
        application.setCreateBy(String.valueOf(getPortalLoginUserId()));
        applicationMapper.insert(application);
        //判断是否为已提交状态
        if (ApplicationEnums.Status.SUBMITTED.getCode().equals(createReqVO.getStatus())){
            createReqVO.setId(application.getId());
            //创建审核记录（左1审核 右边审核）
            createAudit(createReqVO);
        }
        // 返回
        return application.getId();
    }

    @Override
    @Transactional
    public Boolean updateApplication(ApplicationSaveReqVO updateReqVO) throws Exception {
        // 更新
        ApplicationDO updateObj = BeanUtils.toBean(updateReqVO, ApplicationDO.class);
        if (ApplicationEnums.Status.SUBMITTED.getCode().equals(updateReqVO.getStatus())){
            //创建审核记录（左1审核 右边审核）
            createAudit(updateReqVO);
            updateObj.setCommitTime(LocalDateTime.now());
        }
        return applicationMapper.updateById(updateObj) > 0;
    }

    @Override
    public void updateApplicationStatus(Integer applicationId, String status) {
        applicationMapper.updateStatus(applicationId, status);
    }

    @Override
    public ApplicationDO getApplicationDetail(ApplicationPageReqVO pageReqVO) {
        return applicationMapper.getApplicationDetail(pageReqVO);
    }

    @Override
    public Integer getAuditCount() {
        return applicationMapper.getAuditCount(getPortalLoginUsername());
    }

    //创建审核记录
    public void createAudit(ApplicationSaveReqVO createReqVO) throws Exception {
        // 创建审核记录
        approvalRecordService.createAudit(createReqVO);
    }

    @Override
    public void deleteApplication(Integer id) {
        // 删除
        applicationMapper.deleteById(id);
    }

    @Override
        public void deleteApplicationListByIds(List<Integer> ids) {
        // 删除
        applicationMapper.deleteByIds(ids);
        }


    @Override
    public ApplicationDO getApplication(Integer id) {
        return applicationMapper.selectById(id);
    }

    @Override
    public PageResult<ApplicationDO> getApplicationPage(ApplicationPageReqVO pageReqVO) {
        return applicationMapper.selectPage(pageReqVO);
    }

    @Override
    public PageResult<ApplicationDO> getApplicationAuditPage(ApplicationPageReqVO pageReqVO) {
        pageReqVO.setAuditor(String.valueOf(getPortalLoginUsername()));
        //查询消息中心通知人
        NodeConfigDO notify = nodeConfigService.getNodeByCode("NOTIFY");
        // 获取通知节点配置的审批人JSON字符串
        String auditorJson = notify.getAuditor();
        Boolean isNotify = Boolean.FALSE;
        // 解析JSON并获取第一个值（即"测试1"）
        if (StringUtils.isNotBlank(auditorJson) && JSONUtil.isJson(auditorJson)) {
            JSONObject jsonObject = JSONUtil.parseObj(auditorJson);
            // 获取JSON中所有值的集合
            Collection<Object> values = jsonObject.values();
            if (!values.isEmpty()) {
                String notifyPerson = values.iterator().next().toString();
                if (notifyPerson.equals(getPortalLoginUsername())){
                    isNotify = Boolean.TRUE;
                }
            }
        }
        pageReqVO.setIsNotify(isNotify);
        //判断这个人是否为信息中心通知设置人
        return new PageResult<>(
                applicationMapper.getApplicationAuditList(pageReqVO),
                applicationMapper.getApplicationAuditPageCount(pageReqVO)
        );
    }

}